package com.lh.io.nio.channel;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class ChannelTest {

    @Test
    public void test03() throws IOException {
        FileChannel isChannel = null;
        FileChannel osChannel = null;
        FileInputStream is = null;
        FileOutputStream os = null;
        try {
            is = new FileInputStream("");
            os = new FileOutputStream("");

            isChannel = is.getChannel();
            osChannel = os.getChannel();
            //分配缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(1024);

            while (true) {
                // 必须先清空缓冲然后再写入数据到缓冲区
                buffer.clear();
                //读取数据
                int flag = isChannel.read(buffer);
                while (flag == -1) {
                    break;
                }
                //已经读取了数据 ，把缓冲区的模式切换成可读模式
                buffer.flip();
                osChannel.write(buffer);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            is.close();
            os.close();
            isChannel.close();
            osChannel.close();

        }
    }

    @Test
    public void test01() {

        try {
            //1.字节输出流
            FileOutputStream os = new FileOutputStream("test.txt");
            //2.得到字节输出流对应的通道 channel
            FileChannel channel = os.getChannel();
            //3.分配缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            //4.添加
            buffer.put("Hello World!".getBytes());

            buffer.flip();

            channel.write(buffer);
            channel.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Test
    public void test02() {

        try {
            // 1、定义一个文件字节输入流与源文件接通
            FileInputStream is = new FileInputStream("test.txt");
            // 2、需要得到文件字节输入流的文件通道
            FileChannel channel = is.getChannel();
            // 3、定义一个缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            // 4、读取数据到缓冲区
            channel.read(buffer);
            buffer.flip();
            // 5、读取出缓冲区中的数据并输出即可
            String msg = new String(buffer.array(), 0, buffer.remaining());
            System.out.println(msg);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
